<?php
/**
 * AJAX CRUD Controller Class
 * The following variables are available in this template:
 * - $this: the CrudCode object
 *
 * @author HaoLV
 */
Yii::import('application.utilities.OrderService');
Yii::import('application.utilities.Utility');
 
class UsersController extends ControllerBase
{
	public function init() {
            ShortUtil::app()->theme = ADMIN_THEME;
            parent::init();
            $this->registerFancybox();
        }
        
        public function registerFancybox(){
            // Add jQuery library
            // ShortUtil::clientScript()->registerCoreScript('jquery');

            // Add mousewheel plugin (this is optional)
            ShortUtil::registerScriptFile(ShortUtil::themePath() . '/js/fancybox/jquery.mousewheel-3.0.6.pack.js', CClientScript::POS_HEAD);

            // Add fancyBox main JS and CSS files
            ShortUtil::registerScriptFile(ShortUtil::themePath() . '/js/fancybox/jquery.fancybox.js?v=2.0.6');
            ShortUtil::registerCssFile(ShortUtil::themePath().'/js/fancybox/jquery.fancybox.css?v=2.0.6','screen');
            
            // Add Button helper (this is optional)
            // ShortUtil::registerScriptFile(ShortUtil::themePath() . '/js/fancybox/helpers/jquery.fancybox-buttons.css?v=1.0.2');
            // ShortUtil::registerCssFile(ShortUtil::themePath().'/js/fancybox/helpers/jquery.fancybox-buttons.js?v=1.0.2','screen');

            // Add Thumbnail helper (this is optional)
            // ShortUtil::registerScriptFile(ShortUtil::themePath() . '/js/fancybox/helpers/jquery.fancybox-thumbs.css?v=1.0.2');
            // ShortUtil::registerCssFile(ShortUtil::themePath().'/js/fancybox/helpers/jquery.fancybox-thumbs.js?v=1.0.2','screen');
            
            // Add Media helper (this is optional)
            // ShortUtil::registerScriptFile(ShortUtil::themePath() . '/js/fancybox/helpers/jquery.fancybox-media.js?v=1.0.0');
            
            if (isset($_GET['ajax']))
            $this->layout = '//layouts/none';
        }

	/**
	 * Displays a particular model.
	 * @param integer $id the ID of the model to be displayed
	 */
	public function actionView($id)
	{
                $this->render('view', array('model' => $this->loadModel($id)));
	}

	/**
	 * Creates a new model.
	 */
	public function actionCreate()
	{
		$model=new Users;

		// Uncomment the following line if AJAX validation is needed
		// $this->performAjaxValidation($model);

		if(isset($_POST['Users']))
		{
			$model->attributes=$_POST['Users'];
                        $model->createtime = time();
                        $model->lastvisit = time();
                        $model->password = UserModule::encrypting($_POST['Users']['password']);
                        
			if($model->save()){
                            $this->setFlash('Users has been created.');
                            $this->refresh();
                        }
		}

		$this->render('create',array(
			'model'=>$model,
		));
	}

	/**
	 * Updates a particular model.
	 * @param integer $id the ID of the model to be updated
	 */
	public function actionUpdate($id)
	{
		$model=$this->loadModel($id);

		// Uncomment the following line if AJAX validation is needed
		// $this->performAjaxValidation($model);

		if(isset($_POST['Users']))
		{
			$model->attributes=$_POST['Users'];
                        
                        if ($_POST['Users']['password'] != ''){
                            $model->password = UserModule::encrypting($_POST['Users']['password']);
                        }
			if($model->save()){
                            $this->setFlash('Users has been updated.');
                            $this->refresh();
                        }
		}

		$this->render('update',array(
			'model'=>$model,
		));
	}

	/**
	 * Deletes a particular model.
	 * @param integer $id the ID of the model to be deleted
	 */
	public function actionDelete()
	{
		if(Yii::app()->request->isPostRequest)
		{
                    $ids = $_POST['chk'];
                    if (is_array($ids))
                        foreach ($ids as $key)
                            $rs = Users::model()->deleteByPk($key);
                    if (isset($_GET['ajax'])) {
                        echo CHtml::tag ('div', array('class' => 'flash-success'), "Term ID #{$key} has been deleted.");
                        exit;
                    } else {
                        $this->setFlash("Users ID #{$key} has been deleted.");
                        $this->redirect(array('index'));
                    }

		}
		else
			throw new CHttpException(400,'Invalid request. Please do not repeat this request again.');
	}

	/**
	 * Manages all models.
	 */
	public function actionIndex()
	{
		$model=new Users('search');
		$model->unsetAttributes();  // clear any default values
		if(isset($_GET['Users']))
			$model->attributes=$_GET['Users'];

		$this->render('index',array(
			'model'=>$model,
		));
	}

	/**
	 * Returns the data model based on the primary key given in the GET variable.
	 * If the data model is not found, an HTTP exception will be raised.
	 * @param integer the ID of the model to be loaded
	 */
	public function loadModel($id)
	{
		$model=Users::model()->findByPk($id);
		if($model===null)
			throw new CHttpException(404,'The requested page does not exist.');
		return $model;
	}

	/**
	 * Performs the AJAX validation.
	 * @param CModel the model to be validated
	 */
	protected function performAjaxValidation($model)
	{
		if(isset($_POST['ajax']) && $_POST['ajax']==='users-form')
		{
			echo CActiveForm::validate($model);
			ShortUtil::app()->end();
		}
	}
        
        /**
     * Returns the data model based on the primary key given in the GET variable.
     * If the data model is not found, an HTTP exception will be raised.
     * @param integer the primary key value. Defaults to null, meaning using the 'id' GET variable
     */
    public function loadUser($id=null) {
        if ($this->_model === null) {
            if ($id !== null || isset($_GET['id']))
                $this->_model = User::model()->findbyPk($id !== null ? $id : $_GET['id']);
            if ($this->_model === null)
                throw new CHttpException(404, 'The requested page does not exist.');
        }
        return $this->_model;
    }
    
    public function actionOrder() {
        $model = new Orders('search');
        $model->unsetAttributes();  // clear any default values

        if (isset($_GET['Orders']))
            $model->attributes = $_GET['Orders'];

        $this->render('list_order', array(
            'model' => $model,
        ));
    }

    public function actionOrderDetail($id) {
        if (Yii::app()->request->isPostRequest) {
            $model = OrderDetail::model()->findAll(array(
                'condition' => "order_id={$id}"
            ));
            echo CHtml::form();
            echo CHtml::openTag('table', array('width' => '100%', 'style' => 'text-align: center; margin-top: 10px'));
            foreach ($model as $data) :
                $data->attributes = unserialize($data->product);
                echo CHtml::openTag('tr');
                echo CHtml::tag('td', array(), CHtml::image(Yii::app()->baseUrl . '/' . $data->uri) . "<br/>" . $data->name);
                echo CHtml::tag('td', array(), $data->name);
                echo CHtml::tag('td', array(), $data->price);
                echo CHtml::tag('td', array(), $data->quantity);
                echo CHtml::tag('td', array(), $data->sumPrice);
                echo CHtml::closeTag('tr');
            endforeach;

            $order = Orders::model()->findByPk((int) $id);

            echo CHtml::tag('tr', array(), CHtml::tag('td', array('colspan' => 5, 'align' => 'right'), 'Tổng giá trị đơn hàng: <strong style="background: pink">' . Utility::numberFormat($order->total) . '</strong>'));


            echo CHtml::openTag('tr');
            echo CHtml::openTag('td', array('colspan' => 5, 'style' => 'text-align: left; padding: 10px; font: normal 13px Tahoma'));
            $order->attributes = unserialize($order->account);
//            $order->attributes = unserialize($order->shipping);
            echo "<div style='float: left; width: 250px'><b>Thông tin đặt hàng</b><hr/>";
            echo "<div>Họ tên: <strong>{$order->fullname}</strong></div>";
            echo "<div>Phone: <strong>{$order->phone}</strong></div>";
            echo "<div>Email: <strong>{$order->email}</strong></div>";
            echo "<div>Address: <strong>{$order->address}</strong></div></div>";

//            echo "<div style='float: left; width: 250px; margin-left: 20px'><b>Thông tin giao hàng</b><hr/>";
//            echo "<div>Họ tên: <strong>{$order->f}</strong></div>";
//            echo "<div>Phone: <strong>{$order->p}</strong></div>";
//            echo "<div>Email: <strong>{$order->e}</strong></div>";
//            echo "<div>Address: <strong>{$order->a}</strong></div></div>";

            if ($order->status == 0) {
                echo "<div style='float: right;'><b>Xác nhận đơn hàng</b><hr/>" . CHtml::dropDownList('confrim_order', 0, array(
                    0 => '--- Action ---',
                    1 => 'Xác nhận đơn hàng',
                    2 => 'Từ chối - Không có sản phẩm',
                    3 => 'Từ chối - Khách không lấy hàng',
                        ), array(
                    'onchange' => CHtml::ajax(
                            array(
                                'type' => 'POST',
                                'dataType' => 'json',
                                'url' => $this->createUrl('user/updateStatusOrder', array('id' => $order->id)),
                                'success' => 'function(html) {
                                    var json = eval(html);
                                    $("#Order_status_"+json.id).html(json.message);
                                }',
//                                'beforeSend' => '',
                            )
                    ),
                )) . "</div>";
            }
            echo "<div class='clear'>Nhắc nhở: {$order->note}</div>";
//            echo "<div>Thời gian giao hàng: {$order->note}</div>";
            echo CHtml::tag('div', array('align' => 'right'), CHtml::link('Close x', 'javascript:vid(0)', array('onclick' => "$('#Order_{$order->id}').slideUp()")));

            echo CHtml::closeTag('td');
            echo CHtml::closeTag('tr');

            echo CHtml::closeTag('table');
            echo CHtml::endForm();
        }
    }

    public function actionUpdateStatusOrder($id) {
        if (Yii::app()->request->isPostRequest) {
            $row = Orders::model()->updateByPk((int) $id, array('status' => $_POST['confrim_order']));

            $rs = array('id' => $id, 'message' => OrderService::getStatus($_POST['confrim_order']));
            echo json_encode($rs);
        }
    }
}